﻿using AllInOne.Classes;
using AllInOne.MainPages;
using AllInOne.Menu;
using AllInOne.ModelDb;
using AllInOne.Pages;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace AllInOne
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        //异常处理参考网址：https://blog.csdn.net/qq_23018459/article/details/104900225

        /// <summary>
        /// UI线程未捕获异常处理事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            Exception ex = e.Exception;
            string errorTime = "异常时间：" + DateTime.Now.ToString();
            string errorInfo = "异常信息：" + ex.Message;
            string errorSource = "错误源：" + ex.Source;
            string errorType = "运行类型：" + ex.GetType();
            string errorFunction = "异常函数：" + ex.TargetSite;
            string errorTrace = "堆栈信息：" + ex.StackTrace;
            SimpleConsole.WriteError(errorTime + ":" + errorSource + ":" + errorType + ":" + errorInfo + ":" + errorTrace, sender);
        }
        /// <summary>
        /// 软件模式：
        /// 1表示自助机发卡 2表示手动发卡 6当天可拉货物车辆信息维护 7测试侧边栏
        /// </summary>
        private string Mode;

        private static System.Threading.Mutex mutex;
        /// <summary>
        /// 系统最开始进入的页面
        /// </summary>
        /// <param name="e"></param>
        protected override void OnStartup(StartupEventArgs e)
        {
            #region 注释掉 页面事件中有DispatcherUnhandledExceptionEventHandler 事件
            ////UI线程未捕获异常处理事件
            //this.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
            #endregion

            #region Task线程内未捕获异常处理事件
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
            #endregion

            #region 非UI线程未捕获异常处理事件
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            #endregion

            mutex = new System.Threading.Mutex(true, "OnlyRun_CRNS");
            if (mutex.WaitOne(0, false))
            {
                //读取软件配置
                Mode = GetSoftMode_ByAppConifg();
                base.OnStartup(e);
            }
            else
            {
                MessageBox.Show("程序已经在运行！", "提示");
                this.Shutdown();
            }
        }
        void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            try
            {
                e.Handled = true; //把 Handled 属性设为true，表示此异常已处理，程序可以继续运行，不会强制退出 
                SimpleConsole.WriteError("捕获未处理异常:" + e.Exception.Message, null);
            }
            catch (Exception ex)
            {
                SimpleConsole.WriteError("程序发生致命错误，将终止，请联系运营商:" + ex.ToString(), null);
                //此时程序出现严重异常，将强制结束退出
                //MessageBox.Show("程序发生致命错误，将终止，请联系运营商！");
            }
        }

        void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            //task线程内未处理捕获
            SimpleConsole.WriteError("捕获线程内未处理异常：" + e.Exception.Message, null);
            e.SetObserved();//设置该异常已察觉（这样处理后就不会引起程序崩溃）
        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = (Exception)e.ExceptionObject;
            string errorTime = "异常时间：" + DateTime.Now.ToString();
            string errorInfo = "异常信息：" + ex.Message;
            string errorSource = "错误源：" + ex.Source;
            string errorType = "运行类型：" + ex.GetType();
            string errorFunction = "异常函数：" + ex.TargetSite;
            string errorTrace = "堆栈信息：" + ex.StackTrace;
            SimpleConsole.WriteError("全局异常:" + errorTime + ":" + errorSource + ":" + errorType + ":" + errorInfo + ":" + errorTrace, sender);
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            //初始化调用接口地址
            ServiceWebApi.InitProperties(SystemParam.ApiUrl);
            switch (Mode)
            {
                case "自助发卡模式":
                    MainWindow wnd = new MainWindow();
                    wnd.Title = "自助发卡";
                    wnd.Show();
                    break;
                case "手动发卡":
                    Manual_MainWindow Manual = new Manual_MainWindow();
                    Manual.Title = "手动发卡";
                    Manual.Show();
                    break;
                case "门卫数据展示":
                    GuardOfficeWindow guardOfficeWindow = new GuardOfficeWindow();
                    guardOfficeWindow.Title = "门卫数据展示";
                    guardOfficeWindow.Show();
                    break;
                case "装车区数据展示":
                    LoadingAreaWindow law = new LoadingAreaWindow();
                    law.Title = "装车区数据展示";
                    law.Show();
                    break;
                case "物流中心数据展示":
                    LogisticsCentreWindow lcw = new LogisticsCentreWindow();
                    lcw.Title = "物流中心数据展示";
                    lcw.Show();
                    break;
                //case "当天可拉货物车辆信息维护":
                //    Base_VerifyPlate_Window bvw = new Base_VerifyPlate_Window();
                //    bvw.Title = "当天可拉货物车辆信息维护";
                //    bvw.Show();
                //    break;
                case "展示信息侧边栏":
                    ShowInfoWindow bvw = new ShowInfoWindow();
                    bvw.Title = "展示信息侧边栏";
                    bvw.Show();
                    break;

                case "测试页面":
                    //弹出页面
                    PlateGoodsListPage view1 = new PlateGoodsListPage();
                    view1.Title = "测试页面";
                    //view1.Owner = this.parent;
                    view1.ShowInTaskbar = false;
                    List<VerifyPlateList> tempList = new List<VerifyPlateList>();
                    VerifyPlateList temp = new VerifyPlateList();
                    temp.Id = 1;
                    temp.GoodsName = "铁粉";
                    temp.Value1 = "2";
                    temp.Value2 = "发货单位1";
                    temp.Value3 = "收货单位1";
                    tempList.Add(temp);
                    view1.InitPage(tempList);
                    view1.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                    view1.Show();
                    break;
                case "测试车牌页面":
                    //弹出页面
                    PlateInputWin piWin = new PlateInputWin("老车牌");
                    piWin.Show();
                    break;
                default:
                    // Create the startup window
                    MainWindow wnd1 = new MainWindow();
                    // Do stuff here, e.g. to the window
                    wnd1.Title = "自助发卡";
                    // Show the window
                    wnd1.Show();
                    break;
            }
        }
        /// <summary>
        /// 通过软件配置读取软件模式
        /// </summary>
        /// <returns></returns>
        private string GetSoftMode_ByAppConifg()
        {
            try
            {
                //AppSettingsReader reader = new AppSettingsReader();
                //int SendCardModel = (int)reader.GetValue("SendCardModel", typeof(int));
                int SendCardModel = SystemParam.SendCardModel;
                switch (SendCardModel)
                {
                    case 1:
                        return "自助发卡模式";
                    case 2:
                        return "手动发卡模式";
                    case 3:
                        return "门卫数据展示";
                    case 4:
                        return "装车区数据展示";
                    case 5:
                        return "物流中心数据展示";
                    case 6:
                        return "当天可拉货物车辆信息维护";
                    case 7:
                        return "展示信息侧边栏";
                    case 8:
                        return "测试页面";
                    case 9:
                        return "测试车牌页面";
                    default:
                        return "自助发卡模式";
                }
            }
            catch (Exception ex)
            {
                SimpleConsole.WriteError("启动软件读取软件模式出错：" + ex.ToString(), this);
                return "自助发卡模式";
            }
        }
    }
}
